import { extname, join } from 'node:path';
import { readFile, writeFile } from 'node:fs/promises';
import { app, ipcMain, shell } from 'electron';
import { v4 as uuid } from 'uuid';
import { getWindow } from '../utils';
import { appPath } from '../db/connect';
import { WINDOWS } from '../constants';
import type { IpcMainEvent } from 'electron';

export function register () {
  ipcMain.on('openWindow', (_event: IpcMainEvent, type: WindowType) => {
    getWindow(type).show()
  })

  ipcMain.on('closeWindow', (_event: IpcMainEvent, type: WindowType) => {
    getWindow(type).hide()
  })

  ipcMain.on('reloadWindow', (_event: IpcMainEvent, type: WindowType) => {
    getWindow(type).reload()
  })

  ipcMain.on('openAtLogin', (_event: IpcMainEvent, openAtLogin: boolean) => {
    app.setLoginItemSettings({
      openAtLogin,
    })
  })

  ipcMain.handle('getOpenAtLogin', () => {
    const loginItemSettings = app.getLoginItemSettings()
    return loginItemSettings.openAtLogin
  })

  ipcMain.on('max', () => {
    const win = getWindow('manager')
  
    if (win.isMaximized()) {
      win.restore()
    } else {
      win.maximize()
    }
  })

  ipcMain.on('min', () => {
    getWindow('manager').minimize()
  })

  ipcMain.on('close', () => {
    getWindow('manager').hide()
  })

  ipcMain.handle('isMaximized', () => {
    return getWindow('manager').isMaximized()
  })

  ipcMain.on('dragWindow', (_event, type: WindowType, offsetX: number, offsetY: number) => {
    const win = getWindow(type)
    const [currentX, currentY] = win.getPosition()
    const { width, height } = WINDOWS[type].options
    
    win.setBounds({
      x: currentX + offsetX,
      y: currentY + offsetY,
      width,
      height,
    })
  })

  ipcMain.on('openExternal', (_event, url: string) => {
    shell.openExternal(url)
  })

  ipcMain.handle('getHomePath', () => {
    return app.getPath('home')
  })

  ipcMain.handle('saveImage', async (_event, buffer: Buffer, fileName: string) => {
    try {
      const ext = extname(fileName)
      const filePath = join(appPath, `${uuid()}${ext}`)
      await writeFile(filePath, buffer as any)
      return filePath
    } catch (e) {
      return Promise.reject(e)
    }
  })

  ipcMain.handle('loadImage', async (_event, filePath: string) => {
    try {
      const buffer = await readFile(filePath)
      return `data:image/png;base64,${buffer.toString('base64')}`
    } catch (e) {
      return Promise.reject(e)
    }
  })
}
